package com.example.book.filter;

import com.example.book.utils.JdbcUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @Description
 * @ClassName TransactionFilter
 * @Author 山山大魔王
 * @Date 2021/12/5 15:04
 * @Version 1.0
 */
//监听所有业务
@WebFilter(filterName = "TransactionFilter",urlPatterns = {"/*"})
public class TransactionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
            // 提交事务
            JdbcUtils.commitAndClose();
        } catch (Exception e) {
            // 回滚事务
            JdbcUtils.rollbackAndClose();
            e.printStackTrace();
            //把异常抛给Tomcat管理显示友好的错误页面
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {

    }
}
